const {Op} = require('sequelize')

const Cart = require('../model/cart.model')
const Food = require('../model/food.model')

class operationCart {
	async creatOrUpdate(user_id,food_id){
		let res = await Cart.findOne({
			where:{
				[Op.and]:{
					user_id,
					food_id
				}
			}
		})
		if(res){
			await res.increment('number')
			return await res.reload()
		}else{
			const data = await Cart.create({
				user_id,
				food_id
			})
			return data.dataValues
		}
		
	}

	async findCarts(pageNum,pageSize){
		const offset = (pageNum - 1) * pageSize
		const {count,rows} = await Cart.findAndCountAll({
			attributes:['id','number','selected'],
			offset:offset,
			limit:pageSize * 1,
			include:{
				model:Food,
				as:'food_info',
				attributes:['id','food_name','price'],
			}
		})
		return {
			pageNum,
			pageSize,
			total:count,
			list:rows
		}
	}

	async updateCarts({number,selected},id){
		 const res = await Cart.update({number,selected},{
			where:{
				id
			}
		})
		return res
	}

	async removeCart(id){
		console.log(id);
		const res = await Cart.destroy({
			where: {
					id
			}
		  });
		return res>0
	}

	async modifySelected(status){
		console.log(status);
		if(status){
			// 全选
			console.log("全选");
			await Cart.update({selected:true},{
				where:{
					selected:false
				}
			})
		}
		else{
			// 全不选
			console.log("全不选");
			await Cart.update({selected:false},{
				where:{
					selected:true
				}
			})
		}
	}
}

module.exports = new operationCart()